﻿#include "langstring.h"
#include "../../_global.h"
#include "../containerscommon.h"

#ifdef _DEBUG
//#ifdef _CRTDBG_MAP_ALLOC
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
//#endif 
#endif 

LangString::LangString():DataContainerBase(){

}

LangString::LangString(__int64 _ID):DataContainerBase(_ID){

}

LangString::~LangString(){
	
}

long LangString::parse(SPtr<FileContainer> _inFileContainer,long _offsetInData){

	long dataSize;
	char *dataBuf=NULL;

  if(preParse(_inFileContainer,_offsetInData,&dataBuf,&dataSize)!=1)return -1;
	if(dataBuf==NULL)return -2;

	//Разбор контейнера для конкретного типа (этого объекта):
	//if(dataSize<16)return -4;
	setID(getFileContainer().p()->getID());
	long offset=0;
	long res=0;

  memcpy((void *)&ID_langSelector,(void *)dataBuf,8);
  offset+=8;

  memcpy((void *)&ID_Languages,(void *)(dataBuf+offset),8);
  offset+=8;

	IDList_langPairUStrings.setID(-1);
	
	res=IDList_langPairUStrings.parse(getFileContainer(),offset);
	if(res<0)return -2;
	offset+=res;

	return offset;

}

long LangString::parse(){
	if(getFileContainer().isNULLPtr())return -1;
	if(getFileContainer().p()->getContainerType()!=CT_LANG_USTRING)return -3;
	return parse(getFileContainer(),0);
}

int LangString::join(){

	if(preJoin()!=1)return -1;
	if(checkAndSetObjectsAtIDs()<0)return -2;

	//сборка данных в контейнер:
	getFileContainer().p()->setContainerType(CT_LANG_USTRING);
	getFileContainer().p()->setID(getID());

	char* data;
	long size;

	int res=0;
	long sizeData_IDList_langPairUStrings;
		
	IDList_langPairUStrings.join();

	sizeData_IDList_langPairUStrings=IDList_langPairUStrings.getFileContainer().p()->getDataSize();
	size=sizeData_IDList_langPairUStrings+8+8;
	data=new char[size];

	if(ID_langSelector<0)res=-1;
	if(res==0)memcpy((void *)data,(void *)&ID_langSelector,8);

	if(ID_Languages<0)res=-1;
	if(res==0)memcpy((void *)(data+8),(void *)&ID_Languages,8);
	
	if(IDList_langPairUStrings.getFileContainer().p()->getContainerData()==NULL)res=-1;
	if(res==0)memcpy((void *)(data+16),
		               (void *)(IDList_langPairUStrings.getFileContainer().p()->getContainerData()),
									 sizeData_IDList_langPairUStrings);

	getFileContainer().p()->setDataCopy(data,size);
	delete [] data;
	return 0;

}

int LangString::checkAndSetObjectsAtIDs(){
	if(checkAndSet_T_AtID<LangSelector>(&ResManager::getLangSelectorAtID, &langSelector, ID_langSelector)<0)return -1;
	if(checkAndSet_T_AtID<Languages>(&ResManager::getLanguagesAtID, &languages, ID_Languages)<0)return -1;
	if(IDList_langPairUStrings.checkAndSetObjectsAtIDs()<0)return -1;
  return 0;
}

void LangString::setLangSelector(SPtr<LangSelector> _ls){
	langSelector=_ls;
	ID_langSelector=langSelector.p()->getID();
}

void LangString::setLanguages(SPtr<Languages> _lgs){
	languages=_lgs;
	ID_Languages=languages.p()->getID();
}